let tempUrl = require('../models/tempUrl.js'),
    tempUrlModel = tempUrl.tempUrls;
let urlmapping = require('../models/url.js'),
    urlMappingModel = urlmapping.urls;
let mongoose = require('mongoose');
let _ = require('lodash');
let commonMethods = require('../utils/commonMethods');

function insertUrl(req, res, next){
    let url = req.body.url;
    let responseData = req.body.responseData;

    var tempUrlModelObj = new tempUrlModel({
        url:url,
        responseData:responseData,
    });
    tempUrlModelObj.save(function(err, docs){
        if(err){
            next(err);
        } else {
            res.send("SUCCESS");
        }
    });
};

function findResponseDataByUrl(req, res, next){
    let url = req.body.url;

    tempUrlModel.findOne({url:url}, function(err, result){
        if(err){
            next(err);
        } else {
            if(result){
                res.send(result.responseData);
            }else{
                res.send(null);
            }        
        }
    });
};

function clearTempUrl(req, res, next){
    tempUrlModel.remove({},function(err, result){
        if(err){
            next(err);
        }else{
            res.send("SUCCESS")
        }
    })
}

function removeFirstSlash(url) {
    if(url.indexOf('/') === 0){
        return url.replace(new RegExp('/'),'')
    }
    return url;
}

function getAllUrlsByBizKey(req, res, next){
    let bizKeys = JSON.parse(req.body.bizKeys);
    urlMappingModel.find({"bizKey.bizKeyValue":{$in:bizKeys}},function(err, result){
        if(err){
            next(err);
        }else{
            res.send(result)
        }
    })
}

function batchInsertTempUrls(req, res, next){
    let tempUrls = JSON.parse(req.body.tempUrls);
    if(_.isEmpty(req.body.tempUrls)){
        res.send("ERROR");
    }else{
        tempUrlModel.insertMany(tempUrls, function(err, result){
            if(err){
                next(err);
            }else{
                res.send("SUCCESS");
            }
        })
    }
}

module.exports = {
    insertUrl: insertUrl,
    findResponseDataByUrl: findResponseDataByUrl,
    clearTempUrl: clearTempUrl,
    getAllUrlsByBizKey:getAllUrlsByBizKey,
    batchInsertTempUrls : batchInsertTempUrls
}